import workOrderService from "@/api/services/mes/workOrderService";
import TableDictTag from "@/components/grid/TableDictTag";
import { Modal, Table } from "antd";
import type { ColumnsType } from "antd/es/table";
import type React from "react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import type { WorkOrderKitCheck } from "./entity";

interface KitCheckModalProps {
  open: boolean;
	onCancel: () => void;
  workOrderId: React.Key;
}

const columns: ColumnsType<WorkOrderKitCheck> = [
  { title: "物料编码", dataIndex: "materialCode", key: "materialCode" },
  { title: "物料名称", dataIndex: "materialName", key: "materialName" },
  { title: "物料名称", dataIndex: "materialSpec", key: "materialSpec" },
  { title: "总需求数", dataIndex: "totalQty", key: "totalQty" },
  { title: "可用数量", dataIndex: "availableQty", key: "availableQty" },
  {
    title: "是否齐套",
    dataIndex: "isEnough",
    key: "isEnough",
    render: (_, record) => (
      <TableDictTag
        dictCode="system_true_false"
        value={record.isEnough ?? ""}
      />
    ),
  },
];

const KitCheckModal: React.FC<KitCheckModalProps> = ({
  open,
  onCancel,
  workOrderId
}) => {
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState<WorkOrderKitCheck[]>([]);

  useEffect(() => {
    fetchList();
  }, [workOrderId]);

  //加载表格数据
  const fetchList = () => {
    if (!workOrderId) return;

    setLoading(true);
    workOrderService
      .kitCheck(workOrderId)
      .then((res) => {
        setList(res);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  return (
      <Modal title="齐套分析结果" open={open} onCancel={onCancel} footer={null} width={800} destroyOnClose>
      <Table
        columns={columns}
        dataSource={list}
        rowKey="id"
        loading={loading}
        pagination={false}
      />
    </Modal>
  );
};

export default KitCheckModal;
